package com.qyhl.webtv.module_news.news.nanbu;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class NanBuNewsFragment extends BaseFragment implements NanBuNewsContract.NanBuNewsView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refreshLayout;


    private String sectionId;

    private CommonAdapter<NewsBean> commonAdapter;

    private List<NewsBean> mDataList = new ArrayList<>();

    private NanBuNewsPresenter mPresenter;

    private int page = 1;

    private int type;

    public void setType(int type) {
        this.type = type;
    }

    public void setSectionId(String sectionId) {
        this.sectionId = sectionId;
    }

    public static NanBuNewsFragment newInstance(String sectionId, int type) {
        NanBuNewsFragment fragment = new NanBuNewsFragment();
        fragment.setSectionId(sectionId);
        fragment.setType(type);
        return fragment;
    }

    @Override
    public void initImmersionBar() {

    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.news_fragment_nanbu_news, null);
    }

    @Override
    protected void create() {
        mPresenter = new NanBuNewsPresenter(this);

        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        refreshLayout.setEnableLoadMore(true);

        loadMask.setStatus(LoadingLayout.Loading);
        int layoutId;
        if (type == 6) {
            recycleView.setLayoutManager(new GridLayoutManager(getContext(), 2));
            layoutId = R.layout.news_item_nanbu_newslist;
        } else {
            DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
            divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.news_item_leader_divider));
            recycleView.addItemDecoration(divider);
            recycleView.setLayoutManager(new LinearLayoutManager(getContext()));
            layoutId = R.layout.news_item_nanbu_newslist2;
        }

        recycleView.setAdapter(commonAdapter = new CommonAdapter<NewsBean>(getContext(), layoutId, mDataList) {
            @Override
            protected void convert(ViewHolder holder, NewsBean bean, int position) {
                holder.setText(R.id.title, bean.getTitle());
                if (StringUtils.isNotEmpty(bean.getSource())) {
                    holder.setVisible(R.id.column_title, true);
                    holder.setText(R.id.column_title, bean.getSource());
                } else {
                    holder.setVisible(R.id.column_title, false);
                }


                try {
                    int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
                    if (minPlay == 0) {
                        holder.setVisible(R.id.scan_num, false);
                    } else {
                        //判断评论数是否大于最少浏览数
                        if (StringUtils.isEmpty(bean.getHitCount() + "")) {
                            holder.setVisible(R.id.scan_num, false);
                        } else if (Integer.parseInt(bean.getHitCount()) >=
                                minPlay) {
                            holder.setText(R.id.scan_num, StringUtils.transformNum(bean.getHitCount()) + "阅");
                            holder.setVisible(R.id.scan_num, true);
                        } else {
                            holder.setVisible(R.id.scan_num, false);
                        }
                    }

                } catch (Exception e) {
                    holder.setVisible(R.id.scan_num, false);
                }

                try {

                    int commentNum = Integer.parseInt(CommonUtils.getInstance().getCommentNum());
                    if (commentNum == 0) {
                        holder.setVisible(R.id.comment_num, false);
                    } else {
                        //判断评论数是否大于最少评论数
                        if (StringUtils.isEmpty(bean.getCommentCount() + "")) {
                            holder.setVisible(R.id.comment_num, false);
                        } else if (bean.getCommentCount() >=
                                commentNum) {
                            holder.setText(R.id.comment_num, StringUtils.transformNum(bean.getCommentCount() + "") + "评");
                            holder.setVisible(R.id.comment_num, true);
                        } else {
                            holder.setVisible(R.id.comment_num, false);
                        }
                    }
                } catch (Exception e) {
                    holder.setVisible(R.id.comment_num, false);
                }

                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(NanBuNewsFragment.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);
            }
        });

        mPresenter.getData(sectionId, page + "");
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getData(sectionId, page + "");
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getData(sectionId, page + "");
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getData(sectionId, page + "");
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                NewsBean bean = mDataList.get(position);
                switch (mDataList.get(position).getType()) {
                    case "1"://普通新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
                    }
                    break;
                    case "2"://图片新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        bundle.putString("section", bean.getCatalogID());
                        RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
                    }

                    break;
                    case "3"://直播
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("newsId", bean.getID());
                        bundle.putString("liveType", bean.getLivetype());
                        RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
                    }
                    break;
                    case "4"://标题新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        bundle.putString("title", bean.getTitle());
                        bundle.putString("url", bean.getRedirectURL());
                        RouterManager.router(ARouterPathConstant.ADV, bundle);
                    }
                    break;
                    case "5"://视频新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
                    }
                    break;
                    case "8"://互动直播
                        break;
                    case "101"://抓取新闻
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
                    }
                    break;
                    default:
                        break;

                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    @Override
    public void setListData(List<NewsBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();

    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refreshLayout.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！");
            }
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }


}
